/**
 * 
 */
package es.esi.gemde.network.handlers;

import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Shell;

import com.tecnalia.registry.client.EclipseRegistryClient;
import com.tecnalia.registry.client.ui.Activator;
import com.tecnalia.registry.client.ui.preferences.PreferencesRegistry;
import com.tecnalia.registry.resource.Resource;
import com.tecnalia.registry.resource.gemde.ResourceInputOutput;
import com.tecnalia.registry.resource.gemde.ResourceTransformation;
import com.tecnalia.util.eclipse.XEclipse;

import es.esi.gemde.modeltransformator.ModelTransformatorPlugin;
import es.esi.gemde.modeltransformator.service.ITransformation;
import es.esi.gemde.modeltransformator.ui.dialogs.SelectGEMDETransformationDialog;

/**
 * @author Adrian Noguero (adrian.noguero@tecnalia.com)
 * @author Angel Rego (angel.rego@tecnalia.com)
 * 
 */
public class UploadTransformationCommandHandler extends AbstractHandler {

	private static final String TRANSFORMATION_ID_PARAM_ID = "es.esi.gemde.network.commandparameters.transformation";
	
	private static final String LITERAL_UPLOAD_TRANSFORMATION="Upload transformation";
	
	/* (non-Javadoc)
	 * @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent)
	 */
	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		// Get the selected transformation
		String transformationID = event.getParameter(TRANSFORMATION_ID_PARAM_ID);
		ITransformation transformation = null;

		if (transformationID == null || transformationID == "") {
			SelectGEMDETransformationDialog d = new SelectGEMDETransformationDialog(new Shell());
			if (d.open() == Window.OK) {
				transformation = d.getSelectedTransformation();
			}
			else {
				return null;
			}
		}
		else {
			transformation = ModelTransformatorPlugin.getService().getTransformation(transformationID);	
		}

		if (transformation == null) {
			throw new ExecutionException("Provided transformation is not valid. Transformation couldn't be found in the Registry.");
		}

		// Perform upload to the Registry
		try {
			upload(transformation);
			XEclipse.messageBoxInfo(LITERAL_UPLOAD_TRANSFORMATION, "The transformation '"+transformation.getName()+"' was succesfully uploaded to the Registry Server");
		} catch (Exception e) {
			String message=LITERAL_UPLOAD_TRANSFORMATION+". "+transformation.getName()+" failed. "+e.getMessage();
			XEclipse.messageBoxError(LITERAL_UPLOAD_TRANSFORMATION, "The transformation '"+transformation.getName()+"' was succesfully uploaded to the Registry Server");
			throw new ExecutionException(message,e);
		}
		return null;
	}

	/**
	 * Upload a GEMDE Transformation to the RegistryServer.
	 * @see com.tecnalia.registry.RegistryClient
	 * @param transformation
	 * @throws Exception
	 */
	private void upload(ITransformation transformation) throws Exception{
		//get user-password
		String user=Activator.getDefault().getPreferenceStore().getString(PreferencesRegistry.KEY_USER_REGISTRY);
		String password=Activator.getDefault().getPreferenceStore().getString(PreferencesRegistry.KEY_PASWORD_REGISTRY);
		//load Transformation into Resource object
		Map<String,Resource> mapResources=new HashMap<String,Resource>();
		ResourceTransformation resource=new ResourceTransformation();
		resource.name=transformation.getName();
		resource.description=transformation.getDescription();
		resource.engine=transformation.getEngine();
		mapResources.put(resource.id, resource);
		//get inputs
		Map<String,EClass> params=transformation.getInputs();
		for (String id:params.keySet()){
			EClass param=params.get(id);
			ResourceInputOutput res=new ResourceInputOutput();
			res.name=param.getName();
			res.ePackage=param.getEPackage().getNsURI();
			res.eClass=param.getInstanceClass().getName();
			resource.inputs.add(res.id);
			mapResources.put(res.id, res);
		}
		//get outputs
		params=transformation.getOutputs();
		for (String id:params.keySet()){
			EClass param=params.get(id);
			ResourceInputOutput res=new ResourceInputOutput();
			res.name=param.getName();
			res.ePackage=param.getEPackage().toString();
			resource.output.add(res.id);
			mapResources.put(res.id, res);
		}
		//get files
		List<URI> uris=transformation.getTransformationURIs();
		List<String> files=new ArrayList<String>();
		for(URI uri:uris){
			File file=new File(uri);
			files.add(file.getAbsolutePath());
		}
		//perform upload
		EclipseRegistryClient.getInstance().upload(user, password, resource.id, mapResources, files);
	}
}
